/*
 * 文件名：RpiApplyController.java
 * 版权：Copyright by www.infopub.top
 * 描述：
 * 修改人：wuzhiyang
 * 修改时间：2020年1月17日
 * 跟踪单号：
 * 修改单号：
 * 修改内容：
 */

package top.infopub.mgr.cap.web;


import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import top.infopub.mgr.cap.domain.RpiApplyAssist;
import top.infopub.mgr.cap.domain.RpiApplyDomain;
import top.infopub.mgr.cap.service.LoanFinService;
import top.infopub.mgr.cap.service.RpiApplyDetailService;
import top.infopub.mgr.cap.service.RpiApplyService;
import top.infopub.mgr.cap.vo.RpiApplyVo;
import top.infopub.mgr.common.page.ParamPage;
import top.infopub.mgr.common.vo.ErrorCodeEnum;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.flow.web.GenericFlowController;
import top.infopub.mgr.hr.service.OrgInfoService;
import top.infopub.mgr.hr.service.StaffInfoService;
import top.infopub.mgr.util.FileHelper;
import top.infopub.mgr.util.LogUtil;
import top.infopub.mgr.util.LogUtil.AcctionType;
import top.infopub.mgr.util.LogUtil.LogModelType;
import top.infopub.model.cap.RpiApply;
import top.infopub.model.cap.RpiApplyAtt;
import top.infopub.model.cap.RpiApplyDetail;
import top.infopub.model.hr.OrgInfo;
import top.infopub.model.hr.StaffInfo;
import top.infopub.security.util.SessionUserUtils;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.tdp.sys.service.CodeGeneratorConfigService;
import top.infopub.util.IdFactory;

import com.github.pagehelper.Page;
import com.google.common.collect.Lists;


/**
 * 融资-还本付息
 * @author wuzhiyang
 * @version 2020年1月17日
 * @see RpiApplyController
 * @since
 */
@Controller
@RequestMapping("/rpiApply")
public class RpiApplyController extends GenericFlowController {

    @Autowired
    private RpiApplyService rpiApplyService;

    @Autowired
    private RpiApplyDetailService rpiApplyDetailService;

    @Autowired
    private StaffInfoService staffInfoService;

    @Autowired
    private CodeGeneratorConfigService codeGeneratorConfigService;

    @Autowired
    private OrgInfoService orgInfoService;

    @Autowired
    private LoanFinService loanFinService;

    /**
     * 融资-还本付息
     * @return
     */
    @RequestMapping("/list")
    public String list() {
        return "cap/lay-rpiApply-list";
    }

    /**
     * 融资-还本付息-分页查询
     */
    @RequestMapping("/queryDataByCondition")
    @ResponseBody
    public RspVo<RpiApplyDomain> queryDataByCondition(RpiApplyVo rpiApplyVo, ParamPage paramPage) {
        Page<RpiApplyDomain> page = new Page<RpiApplyDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        //查询时，结束日期增加一天
        if (rpiApplyVo.getEndDate() != null) {
            rpiApplyVo.setEndDate(DateUtils.addDays(rpiApplyVo.getEndDate(), 1));
        }
        //查询时，付款申请日期增加一天
        if (rpiApplyVo.getEndRpiApplyDate() != null) {
            rpiApplyVo.setEndRpiApplyDate(DateUtils.addDays(rpiApplyVo.getEndRpiApplyDate(), 1));
        }
        //增加addby
        rpiApplyVo.setAddBy(SessionUserUtils.getSessionUserId());
        page = rpiApplyService.selectByDomainWhere(page, rpiApplyVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    /**
     * 融资-还本付息-分页查询-我审批的
     */
    @RequestMapping("/queryMyCheckDataByCondition")
    @ResponseBody
    public RspVo<RpiApplyDomain> queryMyCheckDataByCondition(RpiApplyVo rpiApplyVo,
                                                             ParamPage paramPage) {
        Page<RpiApplyDomain> page = new Page<RpiApplyDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        //查询时，结束日期增加一天
        if (rpiApplyVo.getEndDate() != null) {
            rpiApplyVo.setEndDate(DateUtils.addDays(rpiApplyVo.getEndDate(), 1));
        }
        //查询时，付款申请日期增加一天
        if (rpiApplyVo.getEndRpiApplyDate() != null) {
            rpiApplyVo.setEndRpiApplyDate(DateUtils.addDays(rpiApplyVo.getEndRpiApplyDate(), 1));
        }
        //增加addby
        rpiApplyVo.setAddBy(SessionUserUtils.getSessionUserId());
        page = rpiApplyService.selectMyCheckByDomainWhere(page, rpiApplyVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    /**
     * 融资-还本付息
     * @return
     */
    @RequestMapping("/add")
    public String toAdd(HttpServletRequest request) {
        String bindOrgId = String.valueOf(SessionUserUtils.getSessionAttribute("bindOrgId"));
        String bindOrgName = String.valueOf(SessionUserUtils.getSessionAttribute("bindOrgName"));
        String bindDeptId = String.valueOf(SessionUserUtils.getSessionAttribute("bindDeptId"));
        String bindDeptName = String.valueOf(SessionUserUtils.getSessionAttribute("bindDeptName"));
        request.setAttribute("bindOrgId", bindOrgId);
        request.setAttribute("bindOrgName", bindOrgName);
        request.setAttribute("bindDeptId", bindDeptId);
        request.setAttribute("bindDeptName", bindDeptName);
        AuthorizationVO authorizationVO = SessionUserUtils.getSessionAttributeForUserDtl();
        StaffInfo staffInfo = staffInfoService.selectByPrimaryKey(authorizationVO.getHrStaffId());
        request.setAttribute("staffName", staffInfo.getStaffName());
        //返回所有融资放款的信息
        request.setAttribute("allProName", loanFinService.queryAllWithOrg());
        return "cap/lay-rpiApply-add";
    }

    /**
     * 融资-还本付息-新增
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping("/save")
    @ResponseBody
    public RspVo save(RpiApplyAssist rpiApplyAssist) {

        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
        String id = IdFactory.getUUIDUpper();
        //融资-付费记录处理
        rpiApplyAssist.setHrDeptId(rpiApplyAssist.getHrDeptid());
        rpiApplyAssist.setHrOrgId(rpiApplyAssist.getHrOrgid());
        rpiApplyAssist.setStaffName(rpiApplyAssist.getStaffname());
        rpiApplyAssist.setHrStaffApplyId(rpiApplyAssist.getHrStaffApplyid());
        String codesAndproCode = rpiApplyAssist.getCodesAndproCode();
        String[] split = codesAndproCode.split("\\_");
        rpiApplyAssist.setProCode(split[1]);
        /*LoanFin loanFin = loanFinService.selectByProCode(split[1], split[0]);*/
        //添加项目名称
        rpiApplyAssist.setProName(split[2]);
        rpiApplyAssist.setId(id);
        rpiApplyAssist.setAddBy(vo.getId());
        rpiApplyAssist.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
        String code = codeGeneratorConfigService.generatorCode("cap_rpi_apply");
        rpiApplyAssist.setCodes(code);
        //处理本金
        rpiApplyAssist.setPayPrincipal(new BigDecimal("0"));
        //处理利息
        rpiApplyAssist.setPayInterest(new BigDecimal("0"));
        // 处理processId
        rpiApplyAssist.setProcessId(IdFactory.getUUIDUpper());
        rpiApplyAssist.setProcessStatus("1");//审批中
        rpiApplyAssist.setUptBy(vo.getId());
        rpiApplyAssist.setUptTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());

        //还本付息申请明细表处理
        List<RpiApplyDetail> rpiApplyDetails = Lists.newLinkedList();
        //还本付息申请明细表数据处理
        String[] accountName = rpiApplyAssist.getAccountName();
        if (accountName != null && accountName.length > 0) {
            for (int i = 0; i < accountName.length; i++ ) {
                String accountname = accountName[i];
                String payType = rpiApplyAssist.getPayType()[i];
                String openBankName = rpiApplyAssist.getOpenBankName()[i];
                String accountNo = rpiApplyAssist.getAccountNo()[i];
                String paySingle = rpiApplyAssist.getPaySingle()[i];
                if (StringUtils.isEmpty(accountname) && StringUtils.isEmpty(accountname)) {
                    continue;
                }
                RpiApplyDetail rpiApplyDetail = new RpiApplyDetail();
                String payfeeApplyDetailId = IdFactory.getUUIDUpper();//自动生成主键
                rpiApplyDetail.setId(payfeeApplyDetailId);
                rpiApplyDetail.setApplyId(id);
                rpiApplyDetail.setAccountName(accountname);
                rpiApplyDetail.setPayType(payType);
                rpiApplyDetail.setAccountNo(accountNo);
                rpiApplyDetail.setOpenBankName(openBankName);
                rpiApplyDetail.setPaySingle(new BigDecimal(paySingle));
                rpiApplyDetail.setAddBy(vo.getId());
                rpiApplyDetail.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
                rpiApplyDetails.add(rpiApplyDetail);
            }
        }

        //上传附件
        List<RpiApplyAtt> rpiApplyAtts = new ArrayList<RpiApplyAtt>();
        //1=贷款合同  
        String[] fileAtt1 = rpiApplyAssist.getFileAtt1();
        if (fileAtt1 != null) {
            for (String file : fileAtt1) {
                RpiApplyAtt rpiApplyAtt = createFileAtt(vo, id, file);
                rpiApplyAtts.add(rpiApplyAtt);
            }
        }
        //2=还本付息表
        String[] fileAtt2 = rpiApplyAssist.getFileAtt2();
        if (fileAtt2 != null) {
            for (String file : fileAtt2) {
                RpiApplyAtt rpiApplyAtt = createFileAtt(vo, id, file);
                rpiApplyAtts.add(rpiApplyAtt);
            }
        }
        //9=其他材料
        String[] fileAtt9 = rpiApplyAssist.getFileAtt9();
        if (fileAtt9 != null) {
            for (String file : fileAtt9) {
                RpiApplyAtt rpiApplyAtt = createFileAtt(vo, id, file);
                rpiApplyAtts.add(rpiApplyAtt);
            }
        }
        rpiApplyService.saveRpiApply(rpiApplyAssist, rpiApplyDetails, rpiApplyAtts);
        RpiApply rpiApply = new RpiApply();
        //处理本金
        RpiApplyDomain selectByApplyId1 = rpiApplyDetailService.selectByApplyId1(id);
        //处理利息
        RpiApplyDomain selectByApplyId2 = rpiApplyDetailService.selectByApplyId2(id);
        if (selectByApplyId1 != null) {
            rpiApply.setPayPrincipal(selectByApplyId1.getSumPay());
        }
        else {
            rpiApply.setPayPrincipal(new BigDecimal(0));
        }
        if (selectByApplyId2 != null) {
            rpiApply.setPayInterest(selectByApplyId2.getSumPay());
        }
        else {
            rpiApply.setPayInterest(new BigDecimal(0));
        }
        rpiApply.setId(id);
        rpiApplyService.updateBySelective(rpiApply);
        LogUtil.bizLog(LogModelType.PROJECT, AcctionType.ADD, "融资管理 -新增融资-还本付息记录：项目名="
                                                              + rpiApplyAssist.getProName(), null);
        return RspVo.getSuccessResponse();
    }

    private RpiApplyAtt createFileAtt(AuthorizationVO vo, String applyId, String file) {
        //资料信息数组
        String[] fileAttStr = file.split("\\|");
        RpiApplyAtt fileAtt = new RpiApplyAtt();
        fileAtt.setId(IdFactory.getUUIDUpper());
        fileAtt.setApplyId(applyId);//还本付息申请id
        fileAtt.setTypes(fileAttStr[0].substring(0, 1));//附件类型 1=贷款合同 2=还本付息表 9=其他材料
        String fileName = fileAttStr[1].substring(0, fileAttStr[1].lastIndexOf("."));
        String suffix = fileAttStr[1].substring(fileAttStr[1].lastIndexOf("."),
            fileAttStr[1].length()).toLowerCase();//后缀转小写
        fileAtt.setFileName(fileName);//文件名
        fileAtt.setFileSuffix(suffix);//文件后缀
        fileAtt.setFilePath(fileAttStr[3]);//文件保存路径
        fileAtt.setAddBy(vo.getId());//添加人
        fileAtt.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());//添加时间
        return fileAtt;
    }

    /**
     * 上传附件
     * @param request
     * @param response
     * @return 
     * @throws IOException 
     * @see
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping("/uploadAtt")
    public @ResponseBody RspVo uploadAtt(HttpServletRequest request)
        throws IOException {
        List<String> returnFileStrList = new ArrayList<>();
        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest)request;
        Map<String, MultipartFile> map = multipartHttpServletRequest.getFileMap();
        if (map != null) {
            for (String name : map.keySet()) {
                MultipartFile file = map.get(name);
                //资料类型
                String types = request.getParameter("types");
                if (StringUtils.isEmpty(types)) {
                    return ErrorCodeEnum.ERROR_COMMON_PARAM.getRspVo("缺少参数");
                }
                // 上传文件
                String fileId = IdFactory.getUUIDSerialNumber();
                // 服务器资源路径
                String serverPath = "rpiApplyAtt";
                String filePath = FileHelper.upload(file, serverPath);
                returnFileStrList.add(types + "|" + file.getOriginalFilename().trim() + "|"
                                      + fileId + "|" + filePath);
                LogUtil.bizLog(LogModelType.PROJECT, AcctionType.ADD, "上传融资合同附件-文件名:" + filePath
                                                                      + "，文件路径:" + filePath, null);
            }
        }
        return RspVo.getSuccessResponse(returnFileStrList);
    }

    /**
     * 根据id查询付款公司信息(带出的)
     * @param id 项目Id
     * @return
     * @see 
     */
    @RequestMapping("/getOrgInfoAllByProCode")
    @ResponseBody
    public Map<String, Object> getOrgInfoAllByProCode(String codesAndproCode) {
        boolean flag = true;
        Map<String, Object> map = new HashMap<String, Object>();
        String[] split = codesAndproCode.split("\\_");
        String proCode = split[1];
        try {
            OrgInfo orgInfo = orgInfoService.queryByProjectCode(proCode);
            map.put("orgInfo", orgInfo);
        }
        catch (Exception e) {
            log.error("根据单据ID获取付款公司信息异常", e);
            flag = false;
        }
        map.put("flag", flag);
        return map;
    }

    /**
     * 根据id查询融资-还本付息详情  > 注意：方法命名必须为：toDealOrDetail
     * @param id 融资-还本付息Id
     * @return
     * @see
     */
    @RequestMapping("/toDealOrDetail")
    public ModelAndView queryById(HttpServletRequest request, String id, String processDealWith) {
        Map<String, Object> map = new HashMap<String, Object>();
        RpiApplyVo rpiApplyVo = rpiApplyService.selectById(id);
        RpiApplyVo applyVo = rpiApplyService.selectByGuid(id);
        rpiApplyVo.setCompName(applyVo.getCompName());
        request.setAttribute("modelDetail", rpiApplyVo);
        map.put("payfeeApplyVo", rpiApplyVo);
        // 审批flag
        request.setAttribute("processDealWith", processDealWith);
        // 审批data
        processData(request, rpiApplyVo.getProcessId());
        return new ModelAndView("cap/lay-rpiApply-detail", map);
    }

    /**
     * 融资还本付息-复制单据
     * @return
     */
    @RequestMapping("/toCopy")
    public String toCopy(HttpServletRequest request) {
        String id = request.getParameter("id");
        RpiApplyVo rpiApplyVo = rpiApplyService.selectById(id);
        RpiApplyVo applyVo = rpiApplyService.selectByGuid(id);
        rpiApplyVo.setCompName(applyVo.getCompName());
        request.setAttribute("rpiApplyVo", rpiApplyVo);
        return "cap/lay-rpiApply-copy";
    }

}
